//
// Created by ziya on 22-9-14.
//

#include "../../include/core/elfloader.h"

extern void parse_elf32(buffer_t* buffer, elf_t* elf);
extern void parse_elf64(buffer_t* buffer, elf_t* elf);

elf_t* parse_elf(buffer_t* buffer) {
    elf_t* elf = Calloc(1, sizeof(elf_t));
    Elf_Ident* ident = (Elf_Ident*)buffer->data;

    // 验证
    if (0x464c457f != ident->e_magic) {
        ERROR_PRINT("不是有效的ELF文件\n");

        goto return_2;
    }

    // 检测是32位还是64位
    u_char class = ident->e_class;
    if (ELFCLASSNONE == class) {
        ERROR_PRINT("非法类别的ELF文件\n");

        goto return_2;
    } else if (ELFCLASS32 == class) {    // 32bit
        buffer_reset(buffer);

        elf->e_type = ELFCLASS32;

        parse_elf32(buffer, elf);
    } else if (ELFCLASS64 == class) {    // 64bit
        buffer_reset(buffer);

        elf->e_type = ELFCLASS64;

        parse_elf64(buffer, elf);
    }

    goto return_1;

return_2:
    free(elf);
    elf = NULL;
return_1:
    return elf;
}